package com.example.demo.example;

/**
 * Created with IntelliJ IDEA.
 * Description
 * User: 杰
 * Date: 2023 -08 -06
 * Time: 15:32
 */

import com.example.demo.common.Consumer;
import com.example.demo.common.MqException;
import com.example.demo.mqclient.Channel;
import com.example.demo.mqclient.Connection;
import com.example.demo.mqclient.ConnectionFactory;
import com.example.demo.mqserver.core.BasicProperties;
import com.example.demo.mqserver.core.ExchangeType;

import java.io.IOException;

/**
 * 该类表示一个消费者. (通过这个类也应该是一个独立的服务器)
 */
public class DemoConsumer {
    public static void main(String[] args) throws IOException, MqException, InterruptedException {
        System.out.println("启动消费者");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setPort(9090);
        factory.setHost("127.0.0.1");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare("testExchange", ExchangeType.DIRECT,true,false,null);
        channel.queueDeclare("testQueue",true,false,false,null);

        channel.basicConsume("testQueue", true, new Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                System.out.println("消费数据");
                System.out.println("consumerTag=" + consumerTag);
                System.out.println("basicProperties=" + basicProperties);
                String bodyString = new String(body,0,body.length);
                System.out.println("body=" + bodyString);
                System.out.println("成功消费!");
            }
        });

        // 进行循环等待
        while (true) {
            Thread.sleep(800);
        }
    }
}
